package cn.rslee.demo.zookeeper;

import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.serialize.SerializableSerializer;
import org.apache.zookeeper.CreateMode;

import java.io.Serializable;

/**
 * Created by rslee on 16-10-14.
 * 对zookeeper进行如下操作：
 * 1. 连接zookeeper服务端
 * 2. 进行CRUD操作
 *
 */
public class ShowCase<T> {

    private final String ZK_SERVER = "127.0.0.1:2181"; //服务端地址，我这里用的是本地zookeeper

    private ZkClient client = null;

    public ShowCase(){
        client = new ZkClient(ZK_SERVER,10000,10000,new SerializableSerializer());
        System.out.println("conneted ok!");
    }

    /**
     * 判断节点是否存在
     * @param nodeName
     * @return
     */
    public boolean checkNodeExist(String nodeName){
        return client.exists(nodeName);
    }

    public void updateNode(String nodeName,T value){
        client.writeData(nodeName,value);
    }

    /**
     * 添加一个节点
     * @param nodeName
     * @param value
     */
    public String addNode(String nodeName,T value){
        if(checkNodeExist(nodeName)){
            //做更新
            updateNode(nodeName,value);
            return nodeName;
        }
        return client.create(nodeName,value, CreateMode.PERSISTENT);
    }

    /**
     * 单独删除一个节点,非级联删除?
     * @param nodeName
     * @return
     */
    public boolean removeSingleNode(String nodeName){
        return client.delete(nodeName);
    }

    public T readNode(String nodeName){
        return client.readData(nodeName);
    }


    public ZkClient getClient(){
        return this.client;
    }



}
